package com.zcsy.manage.web.news;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.PushConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.news.NoticeInfo;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.news.ICellManualService;
import com.zcsy.manage.service.news.INoticeInfoService;
import com.zcsy.manage.service.news.INoticeReadService;
import com.zcsy.manage.service.news.IYellowPageService;
import com.zcsy.manage.service.push.IPushService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: NoticeInfoContreller.java
 * @Package： com.zcsy.manage.web.news
 * @Description: 小区通知控制层管理类
 * @author liuying 1075817474@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年3月29日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/noticeInfo")
public class NoticeInfoContreller {

	@Autowired
	private INoticeInfoService noticeInfoService;

	@Autowired
	private INoticeReadService noticeReadService;
	
	@Autowired
	private ICellInfoService cellInfoService;

	@Autowired
	private IYellowPageService yellowPageService;
	
	@Autowired
	private ICellManualService cellManualService;
	
	@Autowired
	private IDictService dictService;
	
	@Autowired
	private IPushService pushInfoService;

	private static final int NOTICE_TYPE = -1; // 全部通知类型

	/**
	 * @Description 分页获取数据列表<br>
	 * 
	 * @param pNo
	 *            起始页
	 * @param cellId
	 *            小区id
	 * @param title
	 *            标题
	 * @param req
	 *            用户请求
	 * @return 跳转页面URL
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "noticeInfoList", method = RequestMethod.GET)
	public String noticeInfoList(Model model, Integer pNo, Integer pSize, 
			String title, Integer noticeType, HttpServletRequest req) {

		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		if (noticeType == null) {
			noticeType = NOTICE_TYPE;
		}
		
		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);

		//获取当前小区id
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        
		NoticeInfo noticeInfo = new NoticeInfo();

		noticeInfo.setCellId(cellId);

		// 标题不为空时，设置标题
		if (StringUtils.isNotEmpty(title)) {
			noticeInfo.setTitle(title);
		}

		// 标题不为空时，设置标题
		if (noticeType != null) {
			noticeInfo.setType(noticeType);
		}

		noticeInfo.setUserType(user.getUserType());
		
		List<NoticeInfo> noticeInfos = noticeInfoService.selectByKeyword(noticeInfo);
		PageInfo<NoticeInfo> info = new PageInfo<NoticeInfo>(noticeInfos);

		/*List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
		model.addAttribute("cellInfos", cellInfos);*/

		model.addAttribute("noticeInfo", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("cellId", cellId);
		model.addAttribute("title", title);
		model.addAttribute("noticeType", noticeType);

		List<Dict> noticeTypes = dictService.getDictFromCache("noticeType");
		model.addAttribute("noticeTypes", noticeTypes);
		
		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "news/noticeinfo/noticeInfoList";
	}

	/**
	 * @Description 编辑小区通知<br>
	 * @param id
	 *            主键id
	 * @return 跳转页面URL
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "editnoticeInfo", method = RequestMethod.GET)
	public String editnoticeInfo(Model model, String id) {
		try {
			if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				model.addAttribute("type", Constants.SAVE_TYPE);

			} else {
				NoticeInfo noticeInfo = noticeInfoService
						.selectByPrimaryKey(id);
				model.addAttribute("type", Constants.EDIT_TYPE);
				model.addAttribute("noticeInfo", noticeInfo);
				model.addAttribute("noticecellId", noticeInfo.getCellId());
			}
//			List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
//			model.addAttribute("cellInfos", cellInfos);

			// 从缓存不为空则从缓存中获取通知类型，为空则从数据字典获取
			List<Dict> noticeTypes = dictService.getDictFromCache("noticeType");
			model.addAttribute("noticeTypes", noticeTypes);

		} catch (Exception e) {
		}

		return "news/noticeinfo/noticeInfoEdit";
	}

	/**
	 * @Description 保存或更新小区通知<br>
	 * 
	 * @param title
	 *            标题
	 * @param cellId
	 *            小区id
	 * @param container
	 *            内容
	 * @param sort
	 *            排序
	 * @param noticeId
	 *            主键id
	 * @param request
	 *            用户请求
	 * @param response
	 *            响应
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "saveOrUpdateNotice", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson saveOrUpdateNotice(String title, String cellId,
			Integer noticeType, String container, Integer sort,
			String noticeId, String logo, HttpServletRequest request,
			HttpServletResponse response) {
		RequestJson result = new RequestJson();
		User user = (User) request.getSession().getAttribute(
				RequestConstants.USER_SESSION_ID);
		try {
			NoticeInfo record = new NoticeInfo();
			record.setTitle(title);
			record.setCellId(cellId);
			record.setType(noticeType);
			record.setUserAccount(user.getLoginname());
			record.setContent(container);
			record.setSort(sort);
			record.setLogo(logo);

			if (noticeId != "" && !"0".equals(noticeId)) {
				//更新
				record.setId(noticeId);
				record.setUpdateTime(new Date());
				noticeInfoService.update(record);
				result.setSuccess(true);
				LogUtils.insertLog("用户编辑小区通知", user.getId(), request);

				//删除此条通知的所有阅读记录
				noticeReadService.deleteRecordByNoticeId(record.getId());
				
			} else {
				record.setId(UniqueNumberUtils.get18UniqueNumber());
				record.setSendTime(new Date());
				record.setUpdateTime(new Date());
				noticeInfoService.insert(record);
				result.setSuccess(true);
				LogUtils.insertLog("用户新增小区通知", user.getId(), request);
				if (cellId != null && cellId != "") {
					// 插入一条区域，将当前区域所在的小区绑定依赖关系，有依赖的小区不能被删除
					CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
					cellInfo.setIsUsed(Constants.IS_USED);
					cellInfoService.update(cellInfo);
				}
			}
			//推送给业主客户端
			pushInfoService.pushOwnerMsg(record.getId(), PushConstants.PUSH_TYPE_OWNER_CELL_NOTICE);
			LogUtils.insertLog("小区通知被推送给业主客户端", user.getId(), request);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
		}

		return result;
	}

	/**
	 * @Description 根据多个id删除小区通知信息<br>
	 * 
	 * @param iDs
	 *            多个id
	 * @param req
	 *            用户请求
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "deleteNotice", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson deleteNotice(String iDs, HttpServletRequest req) {

		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		try {
			String ids[] = iDs.split("\\,");
			for (int i = 0; i < ids.length; i++) {
				noticeInfoService.delete(ids[i]);
			}
			result.setSuccess(true);
			LogUtils.insertLog("用户删除小区通知", user.getId(), req);

		} catch (NumberFormatException e) {
			result.setSuccess(false);
			result.setMsg("操作失败");
		}

		return result;
	}

	/**
	 * @Description 小区通知信息详情
	 * @param ids
	 *            多个id
	 * @param req
	 *            用户请求
	 * @return 跳转url
	 * @author fangli Fanglwj520@163.com
	 * @date 2016年5月17日
	 * @see
	 */
	@RequestMapping(value = "/noticeInfoDetail", method = RequestMethod.GET)
	public String cellInfoDetail(Model model, String id, HttpServletRequest req) {
		try {
			NoticeInfo noticeInfo = noticeInfoService.selectByPrimaryKey(id);
			if (noticeInfo != null) {
				model.addAttribute("noticeInfo", noticeInfo);
			}
		} catch (Exception e) {
		}
		return "news/noticeinfo/noticeInfoDetail";
	}
	
	/**
	 * @Description 将选中项置顶
	 * @param id 主键id
	 * @param req 用户请求
	 * @return 响应结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年6月12日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id, HttpServletRequest request){
        RequestJson result = new RequestJson();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
        	NoticeInfo noticeInfo = noticeInfoService.selectByPrimaryKey(id);
        	if(noticeInfo != null){
        		noticeInfo.setUpdateTime(DateUtils.getDate());
        		noticeInfoService.updateSort(noticeInfo);
        		LogUtils.insertLog("用户置顶小区通知", user.getId(), request);

        	}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
}
